#include "HufArc.h"
__HufTree * StrToHufTree (unsigned char * str,size_t unbits,size_t len)
{
	__HufTree * head = NULL;
	__HufTree * tmp_1 = NULL;
	__HufTree * tmp_2 = NULL;
	int i = 0;
	int n = 0;
	tmp_1 = head;
	while (i!=len)
	{
	 if ((i==0) && (n==0))
	 {
		tmp_1 = head = (__HufTree * )calloc (1,sizeof(__HufTree));
		envInf.HufTree = tmp_1;
		if (!tmp_1)
			 cl_exit (1,MEMORY_ERR,envInf);
		head->flag |= 1;
		str[i]<<=1;
		n++;
	 }
		 if (!tmp_1->left)
		 {
			 tmp_1->left = (__HufTree *) calloc (1,sizeof(__HufTree));
			 if (!tmp_1->left)
				 cl_exit (1,MEMORY_ERR,envInf);
			 tmp_1->left->top = tmp_1;
			 tmp_1 = tmp_1->left;
			 if (str[i] & 0x80)
			 {
				 if (n != 7)
				 {
					 str[i]<<=1;
					 n++;
					 tmp_1->alpha |=str[i];
					 i++;
					 tmp_1->alpha |=(str[i]>>(8-n));
					 if (i != (len - 1))
						str[i]<<=n;
					 else
						 i++;
					 tmp_1 = tmp_1->top;
				 } else
				 {
					 i++;
					 tmp_1->alpha = str[i];
					 i++;
					 n = 0;
					 tmp_1 = tmp_1->top;
				 }
			 } else
			 {
				 if (n != 7)
				 {
					 tmp_1->flag |= 1;
					 str[i]<<=1;
					 n++;
				 } else
				 {
					 tmp_1->flag |= 1;
					 i++;
					 n = 0;
				 }
			 }
		 } else
			 if (!tmp_1->right)
			 {
				 tmp_1->right = (__HufTree *) calloc (1,sizeof(__HufTree));
				 if (!tmp_1->right)
					 cl_exit (1,MEMORY_ERR,envInf);
				 tmp_1->right->top = tmp_1;
				 tmp_1 = tmp_1->right;
				 if (str[i] & 0x80)
				 {
					 if (n != 7)
					 {
						 str[i]<<=1;
						 n++;
						 tmp_1->alpha |=str[i];
						 i++;
						 tmp_1->alpha |=(str[i]>>(8-n));
						 if (i != (len - 1))
							str[i]<<=n;
						 else
							 i++;
						 tmp_1 = tmp_1->top;
					} else
					 {
						 i++;
						 tmp_1->alpha = str[i];
						 i++;
						 n = 0;
						 tmp_1 = tmp_1->top;
					 }
				 } else
				 {
					 if (n != 7)
					 {
						 tmp_1->flag |= 1;
						 str[i]<<=1;
						 n++;
					 } else
					 {
						 tmp_1->flag |= 1;
						 i++;
						 n = 0;
					 }
				 }
			 } else
			 {
				 tmp_1 = tmp_1->top;
			 }
	}
	return head;
}

